import 'dart:math';

import 'package:flutter_elf/config/component_index.dart';
import 'dart:ui' as ui;

import 'package:flutter_elf/utils/asset_utils.dart';
import 'package:flutter_elf/utils/common_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
class TurnTablePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TurnTablePageState();
  }
}

class TurnTablePageState extends State<TurnTablePage> with SingleTickerProviderStateMixin{
  AnimationController _animationController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initListener();
    init();
  }
  initListener(){
    double rings = 3;//转10圈 出结果
    double totalRings = rings * 2 * pi + pi / 8 ;
    _animationController = AnimationController(vsync: this)..addListener((){
      radius = _animationController.value * totalRings;
      globalPrint('转的角度' + radius.toString());
    })..addStatusListener((AnimationStatus status){
      if(status == AnimationStatus.completed){
//        _animationController.reset();
//        radius = pi / 8;
      }
    });
  }

  init(){
    values['100'] = '积分兑换券';
    values['200'] = '积分兑换券';
    values['300'] = '积分兑换券';
    values['400'] = '积分兑换券';
    values['500'] = '积分兑换券';
    values['600'] = '积分兑换券';
    values['700'] = '积分兑换券';
    values['800'] = '积分兑换券';
  }

  Map<String,String> values = {};
  double radius = pi / 8;
  bool tapIn = false;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: new Column(
        children: [
          FutureBuilder<List<ui.Image>>(
             future: Future.wait<ui.Image>([
               AssetUtils.loadImage(R.staticImageTurnTableClickPng, px(120).toInt(), px(120).toInt()),
               AssetUtils.loadImage(R.staticImageTurnTableBacRedPng, px(120).toInt(), px(50).toInt()),
               AssetUtils.loadImage(R.staticImageTurnTableBacYellowPng, px(120).toInt(), px(50).toInt()),
             ]),
            builder: (context,snap){
               if(!snap.hasData){
                 return Container();
               }
               return GestureDetector(
                 onTapDown: (detail){
                   if(detail.localPosition.dx > 120 && detail.localPosition.dx < 180){
                     if(detail.localPosition.dy > 120 && detail.localPosition.dy < 180){
                        tapIn = true;
                     }
                   }
                 },
                 onTapUp: (detail){
                   if(!tapIn){
                     return;
                   }
                   if(detail.localPosition.dx > 120 && detail.localPosition.dx < 180){
                     if(detail.localPosition.dy > 120 && detail.localPosition.dy < 180){
                       CommonUtils.showToast('点击到了');
                       _animationController.reset();
                       _animationController.animateTo(1,curve: Curves.decelerate,duration: Duration(seconds: 6));
                     }
                   }
                 },
                 child: AnimatedBuilder(
                   animation: _animationController,
                   builder: (context,_){
                     return CustomPaint(
                       size: Size(px(600), px(600)),
                       painter: TurnTableWidget(snap.data[0],snap.data[1],snap.data[2],values,radius),
                     );
                   },
                 ),
               );
            },
          )
        ],
      ),
    );
  }
}

class TurnTableWidget extends CustomPainter{

  final ui.Image clickImage,redBacImage,yellowBacImage;
  final double radius;
  final Map<String,String> values;
  TurnTableWidget(this.clickImage, this.redBacImage, this.yellowBacImage,this.values,this.radius);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.lightBlue
        ..isAntiAlias = true
        ..strokeCap = StrokeCap.butt
        ..strokeWidth = px(10);
    canvas.save();
    drawBigCircle(size,canvas,paint);
    canvas.translate(size.height/2,size.width/2);
    canvas.rotate(radius);
    drawLine(size,canvas,paint);
    drawImageAndText(size,canvas,paint);
    paint.color = Color(0xfff4f4f4);
    canvas.drawCircle(Offset(0,0), px(10), paint);
    canvas.restore();


    canvas.save();
    canvas.drawImage(clickImage,Offset(size.width/2-30,size.width/2-30), paint);
    canvas.restore();
  }

  drawImageAndText(Size size,Canvas canvas,Paint paint){
    canvas.rotate(- pi / 8 );
    for(int i=0;i<8;i++){
      canvas.save();
      canvas.rotate(- pi / 4 * (i+1));
      if(i%2==0)
      canvas.drawImage(redBacImage, Offset(-px(60),(px(60)- size.width / 2 )), paint);
      else
      canvas.drawImage(yellowBacImage, Offset(-px(60),(px(60) - size.width / 2 )), paint);
      drawTextKey(size,canvas,i);
      drawTextValue(size,canvas,i);
      canvas.restore();
    }
  }

  drawTextValue(Size size,Canvas canvas,int index){
    ui.ParagraphBuilder pb = ui.ParagraphBuilder(ui.ParagraphStyle(
      textAlign: TextAlign.center,
      fontWeight: FontWeight.w300,
      fontStyle: FontStyle.normal,
      fontSize: 12,
    ));
    pb.pushStyle(ui.TextStyle(color: Color(0xffadadad)));
    pb.addText('${values.values.toList()[index]}');
    ui.ParagraphConstraints pc = ui.ParagraphConstraints(width: px(80));
//这里需要先layout, 后面才能获取到文字高度
    ui.Paragraph paragraph = pb.build()..layout(pc);
    canvas.drawParagraph(paragraph, Offset(-px(40),(px(120) - size.width / 2 )));
  }

  drawTextKey(Size size,Canvas canvas,int index){
    ui.ParagraphBuilder pb = ui.ParagraphBuilder(ui.ParagraphStyle(
      textAlign: TextAlign.center,
      fontWeight: FontWeight.w300,
      fontStyle: FontStyle.normal,
      fontSize: px(24),
    ));
    pb.pushStyle(ui.TextStyle(color: Colors.white));
    pb.addText('${values.keys.toList()[index]}');
    ui.ParagraphConstraints pc = ui.ParagraphConstraints(width: px(130));
//这里需要先layout, 后面才能获取到文字高度
    ui.Paragraph paragraph = pb.build()..layout(pc);
    canvas.drawParagraph(paragraph, Offset(-px(62),(px(72) - size.width / 2 )));
  }

  drawBigCircle(Size size,Canvas canvas,Paint paint){
    Offset center = Offset(size.height / 2,size.width / 2);
    canvas.drawCircle(center, size.width/2, paint);
    paint.color = Colors.white;
    canvas.drawCircle(center, size.height / 2 -px(32), paint);
  }

  drawLine(Size size,Canvas canvas ,Paint paint){
    for(int i = 0 ;i<16;i++){
      canvas.save();
      canvas.rotate(pi / 8 * i);
      paint.color = Colors.white;
      Offset offset = Offset(0,size.width/2-px(16));
      canvas.drawCircle(offset, 4, paint);
      if(i % 2 == 0){
        paint.strokeWidth = 1;
        paint.color = Color(0xfff4f4f4);
        canvas.drawLine(Offset(0,0), Offset(size.width/2-px(30),0), paint);
      }
      canvas.restore();
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}